﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Platform.ObjectModel.Design;

namespace Platform.ObjectModel.Serializers
{

	public class NativeStreamer : DataObjectStreamer
	{

		public NativeStreamer()
			: base( Globals.Formatters.Native )
		{ }

		public override byte[] ToStream( object value )
		{
			if ( value == null )
				return null;

			switch ( LibraryUtility.GetFieldType( value ) )
			{
				case FieldType.Enum:
				case FieldType.Text:
					return System.Text.Encoding.Default.GetBytes( Convert.ToString( value ) );
				case FieldType.Number:
					return BitConverter.GetBytes( ( double )value );
				case FieldType.Boolean:
					return BitConverter.GetBytes( ( bool )value );
				case FieldType.DateTime:
					return BitConverter.GetBytes( ( ( DateTime )value ).ToBinary() );
				case FieldType.Collection:
					break;
				case FieldType.Object:
					break;
				default:
					break;
			}

			throw new NotImplementedException();
		}

		public override object FromStream( Type valueType, byte[] stream )
		{
			if ( stream == null )
				return Activator.CreateInstance( valueType );

			switch ( LibraryUtility.GetFieldType( valueType ) )
			{
				case FieldType.Enum:
					string value = Encoding.Default.GetString( stream );
					return Enum.Parse( valueType, value );
				case FieldType.Text:
					//return BitConverter.ToString( stream );
					return Encoding.Default.GetString( stream );
				case FieldType.Number:
					return BitConverter.ToDouble( stream, 0 );
				case FieldType.Boolean:
					return BitConverter.ToBoolean( stream, 0 );
				case FieldType.DateTime:
					return DateTime.FromBinary( BitConverter.ToInt64( stream, 0 ) );
				case FieldType.Collection:
					break;
				case FieldType.Object:
					break;
			}

			throw new NotImplementedException();
		}
	}

}
